/**
 * 
 */
package net.frankish.moviebank2.front;

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.swing.JCheckBox;
import javax.swing.JPanel;

import net.frankish.moviebank.back.db.DerbyDatabase;
import net.frankish.moviebank.beans.Genre;

/**
 * @author Frankish
 */
public class GenrePanel extends JPanel{
	private static final long serialVersionUID = 1L;
	
	private AWTEventListener evtDump= null; 
	Collection<Genre> genreList = null;
	HashMap<String,JCheckBox> genreMap = new HashMap<String,JCheckBox>();
	
	private int rows, columns;
	
	public GenrePanel(){
		this(0,1);
	}
	
	public GenrePanel(int r, int c){
		this.rows = r;
		this.columns = c;
		evtDump =  new EventDump(this);
		Toolkit.getDefaultToolkit().addAWTEventListener(evtDump, MouseEvent.MOUSE_EVENT_MASK );
	}
	
	public void refresh(){
		this.removeAll();
		genreMap.clear();
		genreList = DerbyDatabase.findAllGenres();
		this.setLayout(new GridLayout(rows, columns));
		for (Genre genre : genreList) {
			JCheckBox check = new JCheckBox(genre.getName());
			check.setToolTipText(genre.getDescription());
			genreMap.put(genre.getName(), check);
			this.add(check);
		}
	}

	public void selectGenre(Vector<String> genre) {
		for (JCheckBox box : genreMap.values()) {
			box.setSelected(false);
		}
		for (String string : genre) {
			try{
				genreMap.get(string).setSelected(true);
			}catch(NullPointerException ex){
				Logger.getLogger(this.getClass().getName()).warning("Genre ["+string+"] does not exist in database.");
			}
		}
	}
	public Vector<String> getSelectedGenres() {
		Vector<String> result = new Vector<String>();
		for (Entry<String, JCheckBox> element : genreMap.entrySet()) {
			if(element.getValue().isSelected())
				result.add(element.getKey());
		}
		return result;
	}

	private class EventDump implements AWTEventListener{
		GenrePanel panel;
		EventDump(GenrePanel panel){
			this.panel = panel;
		}
		public void eventDispatched(AWTEvent event) {
			if(event instanceof MouseEvent){
				MouseEvent m = (MouseEvent)event;
				if((m.getComponent().getParent() != null) && (m.getComponent().getParent().equals(panel))){
					if(panel.isEnabled() == false)
						m.consume();
				}
			}
		}
		
	}
	
}
